package com.uci.photogam;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Scanner;



import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;


public class ActivityShare extends Activity{
		private final String[] texts = { "Facebook", "Flicker", "Bluetooth",
				"WIFI" };
		
		private final static int FACEBOOK = 0;
		private final static int FLICKR = 1;
		private final static int BLUETOOTH = 2;
		private final static int WIFI = 3;
		
		private GridView gridview;

		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.sharing_menu);
			
			BTnameView = (TextView) findViewById(R.id.state);

			DisplayMetrics metrics = new DisplayMetrics();
			getWindowManager().getDefaultDisplay().getMetrics(metrics);
			
			gridview = (GridView) findViewById(R.id.sharingMenuGridView);
			gridview.setColumnWidth(metrics.widthPixels / 2);
			gridview.setAdapter(new AdapterMainMenu(this, texts, metrics));
			gridview.setOnItemClickListener(new OnItemClickListener(){
				public void onItemClick(AdapterView<?> parent, View v,
						int position, long id) {
					Intent intent;
					V.Log("MENU", texts[position] + " ");
					switch(position){
					case FACEBOOK:
						break;
					case FLICKR:
						break;
					case BLUETOOTH:
						if (mBluetoothAdapter.isEnabled()) {
							Intent serverIntent = new Intent(ActivityShare.this, DeviceListActivity.class);
							startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
						} else {
							Toast.makeText(ActivityShare.this,
									"Bluetooth is not working, please wait a minute",
									Toast.LENGTH_SHORT).show();
						}

						break;
					case WIFI:
						break;
					}
				}
			});
			

			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

			if (mBluetoothAdapter == null) {
				Toast.makeText(this, "Bluetooth is not available",
						Toast.LENGTH_LONG).show();
				finish();
				return;
			}

			mBTService = new BluetoothService(this);
			mBTService.mHandler = mHandler;

			if (mBTService.getState() == mBTService.STATE_NONE) {
				SharedPreferences pref = getSharedPreferences("EMOLED", 0);
				mDeviceAdd = pref.getString("REGISTED_DEVICE_ADD", null);
				// Log.d(TAG,"mDeviceAdd : " + mDeviceAdd.toString());
				if (mDeviceAdd != null) {
					BluetoothDevice device = mBluetoothAdapter
							.getRemoteDevice(mDeviceAdd);
					mDevice = device;
				}
			}

		}

		public static final int MESSAGE_STATE_CHANGE = 1;
		public static final int MESSAGE_READ = 2;
		public static final int MESSAGE_WRITE = 3;
		public static final int MESSAGE_DEVICE_NAME = 4;
		public static final int MESSAGE_TOAST = 5;
		// Key names received from the BluetoothChatService Handler
		public static final String DEVICE_NAME = "device_name";
		public static final String TOAST = "toast";

		public static BluetoothService mBTService = null;
		public static BluetoothAdapter mBluetoothAdapter = null;
		public static String mDeviceAdd = null;

		BluetoothDevice mDevice = null;

		private static final int REQUEST_CONNECT_DEVICE = 21;
		private static final int REQUEST_ENABLE_BT = 22;

		private final Handler mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MESSAGE_STATE_CHANGE:
					switch (msg.arg1) {
					case BluetoothService.STATE_CONNECTED:
						BTnameView.setText("Connected Device : "
								+ mDevice.getName());
						break;
					case BluetoothService.STATE_CONNECTING:
						BTnameView.setText(R.string.title_connecting);
						break;
					case BluetoothService.STATE_LISTEN:
						BTnameView.setText(R.string.title_not_connected);
						break;
					case BluetoothService.STATE_NONE:
						BTnameView.setText(R.string.title_not_connected);
						break;
					}
					break;
				case MESSAGE_WRITE:

					break;
				case MESSAGE_READ:
					System.out.println("received");

					String contactInfo = (String) msg.obj;
					Scanner contactScan = new Scanner(contactInfo);
					contactScan.useDelimiter(";");
					String name = contactScan.next();
					String phoneNum = contactScan.next();

//					if (contactInfo != null) {
//						contactDataSQLiteOpenHelper.insertContact(name, phoneNum, null);
//
//						contacts.add(new ListViewContactsBook (name,phoneNum,null));
//
//						contactArray = contactDataSQLiteOpenHelper.getAllContact();
//
//						adapter.notifyDataSetChanged();
//					} 
					break;
				case MESSAGE_DEVICE_NAME:
					mDevice = (BluetoothDevice) msg.obj;
					break;
				case MESSAGE_TOAST:
					Toast.makeText(getApplicationContext(),
							msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
							.show();
					break;
				}
			}
		};


		public static byte[] Long2Byte(long value) {
			byte result[] = new byte[8];
			result[0] = ((byte) (value >> 56));
			result[1] = ((byte) (value >> 48));
			result[2] = ((byte) (value >> 40));
			result[3] = ((byte) (value >> 32));
			result[4] = ((byte) (value >> 24));
			result[5] = ((byte) (value >> 16));
			result[6] = ((byte) (value >> 8));
			result[7] = ((byte) (value));
			return result;
		}

		TextView BTnameView;


		@Override
		protected void onStart() {
			// TODO Auto-generated method stub
			super.onStart();

			if (!mBluetoothAdapter.isEnabled()) {
				Intent enableIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
				// Otherwise, setup the chat session
			} else {
				if (mBTService == null)
					; // setupChat();
			}
		}

		
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			// TODO Auto-generated method stub
			super.onActivityResult(requestCode, resultCode, data);
			if(requestCode == REQUEST_CONNECT_DEVICE){
				if (resultCode == Activity.RESULT_OK) {
					// Get the device MAC address
					mDeviceAdd = data.getExtras().getString(
							DeviceListActivity.EXTRA_DEVICE_ADDRESS);
					// Get the BLuetoothDevice object
					mDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAdd);
					// Attempt to connect to the device
					mBTService.connect(mDevice);
				}
			}else if(requestCode == REQUEST_ENABLE_BT){
				if (mBTService != null && mBluetoothAdapter.isEnabled()) {
					// Only if the state is STATE_NONE, do we know that we
					// haven't started already
					if (mBTService.getState() == BluetoothService.STATE_NONE) {
						// Start the Bluetooth chat services
						mBTService.start();
					}
				}

			}else {
				// User did not enable Bluetooth or an error occured
				Toast.makeText(this, R.string.bt_not_enabled_leaving,
						Toast.LENGTH_SHORT).show();
				finish();
			}
		}

		@Override
		protected void onPause() {
			// TODO Auto-generated method stub
			super.onPause();
		}

		@Override
		protected void onDestroy() {
			// TODO Auto-generated method stub
			mBTService.stop();
			super.onDestroy();
		}


		private void sendMessageImage(String message) {
			// Check that we're actually connected before trying anything
			if (mBTService.getState() != BluetoothService.STATE_CONNECTED) {
				return;
			}
			if (message == null) {
				byte[] filenamelengthnull = new byte[4];
				mBTService.write(filenamelengthnull);
				return;
			}

			// Check that there's actually something to send
			if (message.length() > 0) {

				sendMessage(message);
			}
		}

		private void sendMessage(String message) {
			// Check that we're actually connected before trying anything
			if (mBTService.getState() != BluetoothService.STATE_CONNECTED) {
				// Toast.makeText(this, R.string.not_connected,
				// Toast.LENGTH_SHORT).show();
				return;
			}

			// Check that there's actually something to send
			if (message.length() > 0) {
				// Get the message bytes and tell the BluetoothChatService to write
				byte[] send = message.getBytes();
				int bufferlength = send.length;

				byte[] bufferlengtharray = new byte[4];

				bufferlengtharray = intTobyteArray(bufferlength);

				mBTService.write(bufferlengtharray);
				mBTService.write(send);
			}
		}

		byte[] intTobyteArray(int integer) {
			ByteBuffer buff = ByteBuffer.allocate(4);
			buff.putInt(integer);
			buff.order(ByteOrder.BIG_ENDIAN);
			return buff.array();
		}


		@Override
		protected void onResume() {
			// TODO Auto-generated method stub
			super.onResume();
			if (mBTService != null && mBluetoothAdapter.isEnabled()) {
				// Only if the state is STATE_NONE, do we know that we haven't
				// started already
				if (mBTService.getState() == BluetoothService.STATE_NONE) {
					// Start the Bluetooth chat services
					mBTService.start();
				}
			}
		}

}
